<template>
  <div class="contacts-container">
    <!-- 左侧联系人列表 -->
    <div class="contacts-view">
      <el-header class="view-header">
        <h2>联系人</h2>
      </el-header>
      <el-scrollbar class="view-content">
        <el-collapse v-model="activeNames">
          <el-collapse-item title="好友" name="friends">
            <div
              v-for="(friend, index) in friends"
              :key="'friend-'+index"
              class="contact-item"
              :class="{ 'active': activeContact && activeContact.id === friend.id }"
              @click="showContactDetails(friend)"
            >
              <el-avatar :size="40" :src="friend.avatar" />
              <span class="contact-name">{{ friend.name }}</span>
            </div>
          </el-collapse-item>
          <el-collapse-item title="群聊" name="groups">
            <div
              v-for="(group, index) in groups"
              :key="'group-'+index"
              class="contact-item"
              :class="{ 'active': activeContact && activeContact.id === group.id }"
              @click="showContactDetails(group)"
            >
              <el-avatar :size="40" :src="group.avatar" />
              <span class="contact-name">{{ group.name }}</span>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-scrollbar>
    </div>

    <!-- 右侧区域 -->
    <div class="right-panel">
      <!-- 联系人详情 -->
      <div class="contact-details" v-if="activeContact && !showChat">
        <div class="details-wrapper">
          <div class="details-header">
            <div class="header-top">
              <el-avatar :size="60" :src="activeContact.avatar" />
              <h3>{{ activeContact.remark || activeContact.name }}</h3>
            </div>
            <div class="action-buttons">
              <el-button type="primary" plain @click="startChat">
                <el-icon><ChatDotRound /></el-icon>
                <span>发消息</span>
              </el-button>
              <el-button type="success" plain @click="startVoiceCall">
                <el-icon><Phone /></el-icon>
                <span>语音聊天</span>
              </el-button>
              <el-button type="warning" plain @click="startVideoCall">
                <el-icon><VideoCamera /></el-icon>
                <span>视频聊天</span>
              </el-button>
            </div>
          </div>

          <el-divider />

          <div class="details-content">
            <div class="detail-item">
              <span class="detail-label">微信号：</span>
              <span class="detail-value">{{ activeContact.wechatId || '未设置' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">地区：</span>
              <span class="detail-value">{{ activeContact.region || '未设置' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">备注：</span>
              <span class="detail-value">
                <el-button link type="primary" @click="editRemark">
                  {{ activeContact.remark || '点击添加备注' }}
                </el-button>
              </span>
            </div>
            <div class="detail-item">
              <span class="detail-label">朋友权限：</span>
              <span class="detail-value">
                <el-radio-group v-model="activeContact.permission" size="small">
                  <el-radio-button :value="'all'">聊天、朋友圈等</el-radio-button>
                  <el-radio-button :value="'chatOnly'">仅聊天</el-radio-button>
                </el-radio-group>
              </span>
            </div>
            <div class="detail-item">
              <span class="detail-label">个性签名：</span>
              <span class="detail-value">{{ activeContact.signature || '未设置' }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">来源：</span>
              <span class="detail-value">{{ activeContact.source || '未设置' }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 聊天组件 -->
      <ChatDetail
        v-if="showChat && activeContact"
        :user="activeContact"
        :messages="chatMessages"
        @send-msg="handleSendMsg"
        @back="showChat = false"
      />

      <!-- 无选中联系人时的提示 -->
      <div class="empty-details" v-if="!activeContact && !showChat">
        <el-empty description="请从左侧选择联系人查看详情" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, markRaw } from 'vue'
import {
  ElMessageBox,
  ElMessage,
  ElButton,
  ElRadioGroup,
  ElRadioButton
} from 'element-plus'
import {
  ChatDotRound,
  Phone,
  VideoCamera
} from '@element-plus/icons-vue'
import ChatDetail from './ChatDetail.vue'

// 解决组件被错误响应式化的警告
defineOptions({
  markRaw: true
})

const activeNames = ref(['friends', 'groups'])
const activeContact = ref(null)
const showChat = ref(false)
const chatMessages = ref([])

// 模拟好友数据
const friends = ref([
  markRaw({
    id: 1,
    name: '阿发',
    avatar: 'https://picsum.photos/40/40?random=101',
    wechatId: '158158',
    region: '阿根廷 里奥加耶戈斯',
    signature: '趁年轻，折腾吧',
    source: '通过搜索手机号添加',
    permission: 'chatOnly'
  }),
  ...Array.from({ length: 9 }, (_, i) => markRaw({
    id: i + 2,
    name: `好友 ${i + 2}`,
    avatar: `https://picsum.photos/40/40?random=${i + 102}`,
    wechatId: `wx${Math.floor(Math.random() * 1000000)}`,
    region: ['中国 北京', '美国 纽约', '日本 东京', '英国 伦敦'][Math.floor(Math.random() * 4)],
    signature: ['生活不止眼前的苟且', '热爱可抵岁月漫长', '保持热爱，奔赴山海'][Math.floor(Math.random() * 3)],
    source: ['通过群聊添加', '通过名片分享', '通过搜索微信号'][Math.floor(Math.random() * 3)],
    permission: Math.random() > 0.5 ? 'all' : 'chatOnly'
  }))
])

// 模拟群聊数据
const groups = ref(
  Array.from({ length: 5 }, (_, i) => markRaw({
    id: i + 100,
    name: `群聊 ${i + 1}`,
    avatar: `https://picsum.photos/40/40?random=${i + 200}`,
    memberCount: Math.floor(Math.random() * 100) + 10
  }))
)

// 显示联系人详情
const showContactDetails = (contact) => {
  activeContact.value = markRaw(contact)
  showChat.value = false
}

// 编辑备注
const editRemark = () => {
  ElMessageBox.prompt('请输入备注名', '设置备注', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: activeContact.value.remark || activeContact.value.name
  }).then(({ value }) => {
    activeContact.value.remark = value
    ElMessage.success('备注设置成功')
  }).catch(() => {
    ElMessage.info('取消备注设置')
  })
}

// 开始聊天
const startChat = () => {
  // 加载模拟消息
  chatMessages.value = [
    { id: 1, text: '你好！', isSelf: false, time: new Date(Date.now() - 3600000) },
    { id: 2, text: '你好，有什么可以帮你的吗？', isSelf: true, time: new Date(Date.now() - 1800000) },
    { id: 3, text: '我想咨询一些产品信息', isSelf: false, time: new Date() }
  ]
  showChat.value = true
}

// 处理发送消息
const handleSendMsg = ({ text }) => {
  const newMsg = {
    id: Date.now(),
    text,
    isSelf: true,
    time: new Date()
  }
  chatMessages.value.push(newMsg)

  // 模拟回复
  setTimeout(() => {
    const replyMsg = {
      id: Date.now() + 1,
      text: '收到你的消息了，稍后回复你。',
      isSelf: false,
      time: new Date()
    }
    chatMessages.value.push(replyMsg)
  }, 1000)
}

// 语音聊天
const startVoiceCall = () => {
  ElMessage.success(`正在呼叫 ${activeContact.value.name} 语音聊天`)
}

// 视频聊天
const startVideoCall = () => {
  ElMessage.success(`正在呼叫 ${activeContact.value.name} 视频聊天`)
}

// 初始化时默认选中第一个好友
onMounted(() => {
  if (friends.value.length > 0) {
    activeContact.value = markRaw(friends.value[0])
  }
})
</script>

<style lang="scss" scoped>
.contacts-container {
  display: flex;
  height: 100%;

  .contacts-view {
    width: 280px;
    height: 100%;
    border-right: 1px solid #e6e6e6;
    display: flex;
    flex-direction: column;

    .view-header {
      border-bottom: 1px solid #e6e6e6;
      display: flex;
      align-items: center;
      padding: 0 20px;
    }

    .view-content {
      flex: 1;
      padding: 10px;
    }

    .contact-item {
      display: flex;
      align-items: center;
      padding: 10px;
      cursor: pointer;
      border-radius: 4px;
      transition: background-color 0.3s;

      &:hover {
        background-color: #f5f5f5;
      }

      &.active {
        background-color: #e6f7ff;
      }

      .contact-name {
        margin-left: 10px;
      }
    }
  }

  .right-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    position: relative;
  }

  .contact-details {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    display: flex;
    justify-content: center;

    .details-wrapper {
      width: 100%;
      max-width: 600px;

      .details-header {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 20px;
        margin-bottom: 20px;
        text-align: center;

        .header-top {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 10px;
          width: 100%;

          h3 {
            margin: 0;
          }
        }

        .action-buttons {
          display: flex;
          justify-content: center;
          gap: 10px;
          position: absolute;
          bottom: 35%;
          width: 100%;
          flex-wrap: wrap;

          .el-button {
            display: flex;
            align-items: center;
            gap: 5px;
          }
        }
      }

      .details-content {
        padding: 0 20px;

        .detail-item {
          display: flex;
          margin-bottom: 15px;
          align-items: center;

          .detail-label {
            width: 100px;
            color: #888;
            text-align: right;
            padding-right: 15px;
          }

          .detail-value {
            flex: 1;

            .el-radio-group {
              margin-left: -10px;
            }
          }
        }
      }
    }
  }

  .empty-details {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #888;
  }
}
</style>
